<?php
require_once('includes/config.php');
require_once('includes/functions/func.global.php');
require_once('includes/functions/func.users.php');
require_once('includes/classes/class.template_engine.php');
require_once('includes/lang/lang_'.$config['lang'].'.php');

// Start the session
session_start();

// Connect to the database
db_connect($config);

// Check if the user has a remember cookie set
checkremember($config);

// Check that the user is logged in
logincheck();

// Get site categories
$cats = get_cats($config,$lang);

if(!isset($_GET['page']))
{
	$_GET['page'] = 1;
}
if(!isset($_GET['cmd']))
{
	$_GET['cmd'] = 'inbox';
}

if(!$config['mailbox_en'])
{
	exit($lang['PMDISABLED']);
}

switch ($_GET['cmd']) 
{
	case 'delete':	
		$message_id = mysql_num_rows(mysql_query("SELECT 1 FROM `".$config['db']['pre']."inbox` WHERE `message_id` = '".validate_input($_GET['id'])."' AND `message_to` = '".$_SESSION['duser']['id']."' LIMIT 1"));
	
		if($message_id)
		{
			mysql_query("DELETE FROM `".$config['db']['pre']."inbox` WHERE `message_id` = '".validate_input($_GET['id'])."' AND `message_to` = '".$_SESSION['duser']['id']."' LIMIT 1");
		}
		
		header("Location: private.php");
		exit;
		break;
	case 'inbox':
		$messages = array();
		$users = array();
		$user_where = '';
		
		$query = "SELECT message_id,message_subject,message_date,message_read,message_from FROM `".$config['db']['pre']."inbox` WHERE message_to='".$_SESSION['duser']['id']."' ORDER BY message_id DESC LIMIT ".validate_input(($_GET['page']-1)*15).",15";
		$query_result = @mysql_query ($query) OR error(mysql_error());
		while ($info = @mysql_fetch_array($query_result))
		{
			$messages[$info['message_id']]['id'] = $info['message_id'];
			$messages[$info['message_id']]['subject'] = $info['message_subject'];
			$messages[$info['message_id']]['date'] = date("Y-m-d H:i:s",$info['message_date']);
			$messages[$info['message_id']]['read'] = $info['message_read'];
			$messages[$info['message_id']]['from_id'] = $info['message_from'];
			
			if($user_where == '')
			{
				$user_where = "user_id='".$info['message_from']."'";
			}
			else
			{
				$user_where.= " OR user_id='".$info['message_from']."'";
			}
		}
		
		if($user_where != '')
		{
			$query = "SELECT user_id,username FROM `".$config['db']['pre']."users` WHERE ".$user_where." LIMIT 15";
			$query_result = @mysql_query ($query) OR error(mysql_error());
			while ($info = @mysql_fetch_array($query_result))
			{
				$users[$info['user_id']] = $info['username'];
			}
		}
		
		foreach ($messages as $key => $value)
		{
				if(isset($users[$value['from_id']]))
				{
					$messages[$key]['from_username'] = $users[$value['from_id']];
				}
				else
				{
					$messages[$key]['from_username'] = '';
				}
		}
	
		$page = new HtmlTemplate ('templates/' . $config['tpl_name'] . '/private_inbox.html');
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$lang['INBOX']));
		$page->SetLoop ('MESSAGES', $messages);
		$page->SetParameter ('MESSAGE_COUNT', count($messages));
		$page->SetLoop ('CATS', $cats);
		if(isset($_SESSION['duser']['id']))
		{
			$page->SetParameter ('LOGGEDIN', 1);
		}
		else
		{
			$page->SetParameter ('LOGGEDIN', 0);
		}
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->CreatePageEcho($lang,$config);
		break;
	case 'send':
		$message_subject = '';
		$message_body = '';
		$errors = 0;
		
		if(isset($_POST['mid']))
		{
			$_GET['mid'] = $_POST['mid'];
		}
		if(isset($_POST['toid']))
		{
			$_GET['toid'] = $_POST['toid'];
		}
		
		if(isset($_GET['mid']))
		{
			$mess_details = mysql_fetch_row(mysql_query("SELECT message_from,message_subject,message_body,message_date FROM `".$config['db']['pre']."inbox` WHERE message_to='".$_SESSION['duser']['id']."' AND message_id='".validate_input($_GET['mid'])."' LIMIT 1"));
			
			if(isset($mess_details[1]))
			{
				$_GET['toid'] = $mess_details[0];
			}
		}
		
		if($_GET['toid'] == $_SESSION['duser']['id'])
		{
			$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/message.html");
			$page->SetParameter ('SUBJECT',$lang['INBOX']);
			$page->SetParameter ('MESSAGE',$lang['NOMESSELF']);
			$page->SetLoop ('CATS', $cats);
			if(isset($_SESSION['duser']['id']))
			{
				$page->SetParameter ('LOGGEDIN', 1);
			}
			else
			{
				$page->SetParameter ('LOGGEDIN', 0);
			}
			$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,$lang['INBOX']));
			$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
			$page->CreatePageEcho($lang,$config);
			exit;
		}
		
		if(!isset($_GET['toid']))
		{
			$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/message.html");
			$page->SetParameter ('SUBJECT',$lang['INBOX']);
			$page->SetParameter ('MESSAGE',$lang['MESSVALUSER']);
			$page->SetLoop ('CATS', $cats);
			if(isset($_SESSION['duser']['id']))
			{
				$page->SetParameter ('LOGGEDIN', 1);
			}
			else
			{
				$page->SetParameter ('LOGGEDIN', 0);
			}
			$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,$lang['INBOX']));
			$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
			$page->CreatePageEcho($lang,$config);
			exit;
		}
		
		$user_details = mysql_fetch_row(mysql_query("SELECT username FROM `".$config['db']['pre']."users` WHERE user_id='".validate_input($_GET['toid'])."' LIMIT 1"));
		
		if(!$user_details[0])
		{
			$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/message.html");
			$page->SetParameter ('SUBJECT',$lang['INBOX']);
			$page->SetParameter ('MESSAGE',$lang['NOVALIDUSER']);
			$page->SetLoop ('CATS', $cats);
			if(isset($_SESSION['duser']['id']))
			{
				$page->SetParameter ('LOGGEDIN', 1);
			}
			else
			{
				$page->SetParameter ('LOGGEDIN', 0);
			}
			$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$cats,$lang['INBOX']));
			$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
			$page->CreatePageEcho($lang,$config);
			exit;
		}
		
		if(isset($_POST['body']))
		{
			// Remove HTML from subject and body
			$_POST['body'] = strip_tags($_POST['body']);
			$_POST['subject'] = strip_tags($_POST['subject']);
			// Limit the length of both fields
			$_POST['body'] = substr($_POST['body'],0,2000);
			$_POST['subject'] = substr($_POST['subject'],0,50);
			
			if(trim($_POST['subject']) == '')
			{
				$errors++;
			}
			if(trim($_POST['body']) == '')
			{
				$errors++;
			}
			
			if($errors == 0)
			{			
				mysql_query("INSERT INTO `".$config['db']['pre']."inbox` ( `message_from` , `message_to` , `message_date` , `message_subject` , `message_body` , `message_read` ) VALUES ('".$_SESSION['duser']['id']."', '".validate_input($_GET['toid'])."', '".time()."', '".validate_input($_POST['subject'])."', '".validate_input($_POST['body'])."', '0');");
			
				header("Location: private.php");
			}
		}
		
		if($errors > 0)
		{
			$message_subject = stripslashes($_POST['subject']);
			$message_body = stripslashes($_POST['body']);
		}
		else
		{
			if(isset($mess_details[1]))
			{
				if(eregi($lang['RE'].':',$mess_details[1]))
				{
					$message_subject = stripslashes($mess_details[1]);
				}
				else
				{
					$message_subject = $lang['RE'].': '.stripslashes($mess_details[1]);
				}
				
				$message_body = "\r\n\r\n\r\n\r\n---------- ".$lang['ORIGMSG']." ----------\r\n".$lang['FROM'].": ".$user_details[0]."\r\n".$lang['SENT'].": ".date("Y-m-d H:i:s",$mess_details[3])."\r\n-------------------------------------\r\n\r\n".stripslashes($mess_details[2]);
			}
		}
	
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/private_send.html");
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$lang['INBOX']));
		$page->SetParameter ('MESSAGE_SUBJECT', $message_subject);
		$page->SetParameter ('MESSAGE_BODY', $message_body);
		$page->SetParameter ('TO_USERNAME', $user_details[0]);
		$page->SetParameter ('TO_ID', $_GET['toid']);
		$page->SetLoop ('CATS', $cats);
		if(isset($_SESSION['duser']['id']))
		{
			$page->SetParameter ('LOGGEDIN', 1);
		}
		else
		{
			$page->SetParameter ('LOGGEDIN', 0);
		}
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->CreatePageEcho($lang,$config);
		break;
	case 'read':
		$message_info = mysql_fetch_array(mysql_query("SELECT * FROM `".$config['db']['pre']."inbox` WHERE message_id='".validate_input($_GET['id'])."' LIMIT 1"));
	
		if(!isset($message_info['message_id']))
		{
			exit;
		}
		else
		{
			if(!$message_info['message_id'])
			{
				exit;
			}
		}
	
		if($message_info['message_read'] == 0)
		{
			mysql_query("UPDATE `".$config['db']['pre']."inbox` SET `message_read` = '1' WHERE `message_id` = '".validate_input($_GET['id'])."' LIMIT 1 ;");
		}
		
		$user_info = mysql_fetch_row(mysql_query("SELECT username FROM `".$config['db']['pre']."users` WHERE user_id='".validate_input($message_info['message_from'])."' LIMIT 1"));
	
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/private_read.html");
		$page->SetParameter ('OVERALL_HEADER', create_header($config,$lang,$lang['INBOX']));
		$page->SetParameter ('SUBJECT', stripslashes($message_info['message_subject']));
		$page->SetParameter ('DATE', date("Y-m-d H:i:s",$message_info['message_date']));
		$page->SetParameter ('BODY', nl2br(stripslashes($message_info['message_body'])));
		$page->SetParameter ('MESSAGE_ID', $message_info['message_id']);
		$page->SetParameter ('USERNAME', $user_info[0]);
		$page->SetLoop ('CATS', $cats);
		if(isset($_SESSION['duser']['id']))
		{
			$page->SetParameter ('LOGGEDIN', 1);
		}
		else
		{
			$page->SetParameter ('LOGGEDIN', 0);
		}
		$page->SetParameter ('OVERALL_FOOTER', create_footer($config,$lang));
		$page->CreatePageEcho($lang,$config);
		break;
}
?>